package mtm.ui.resizable;

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;

import javax.swing.SwingConstants;
import javax.swing.border.Border;

/**
 * Resizable border
 */
public class ResizableBorder implements Border {
	
	/**
	 * Inset size
	 */
	private int insetSize = 8;

	
	/**
	 * Constructor with initial inset size
	 * @param insetSize
	 */
	public ResizableBorder(int insetSize) {
		this.insetSize = insetSize;
	}

	
	/**
	 * Return inset of border
	 */
	public Insets getBorderInsets(Component component) {
		return new Insets(insetSize, insetSize, insetSize, insetSize);
	}

	
	/**
	 * Check this border is opaque or not
	 */
	public boolean isBorderOpaque() {
		return false;
	}

	
	/**
	 * Draw border
	 */
	public void paintBorder(Component component, Graphics g, int x, int y,
			int w, int h) {
		
		Rectangle rect = getRectangle(0, 0, w, h, SwingConstants.SOUTH);
		g.setColor(Color.WHITE);
		g.fillRect(rect.x, rect.y, rect.width - 1, rect.height - 1);
		g.setColor(Color.RED);
		g.drawRect(rect.x, rect.y, rect.width - 1, rect.height - 1);
	}

	
	private Rectangle getRectangle(int x, int y, int w, int h, int location) {
		switch (location) {
			case SwingConstants.SOUTH:
				return new Rectangle(x + w / 2 - insetSize / 2, y + h - insetSize, insetSize, insetSize);
			}
		
		return null;
	}

	
	/**
	 * Return type of mouse cursor
	 * @param me
	 * @return
	 */
	public int getCursor(MouseEvent me) {
		Component c = me.getComponent();
		int w = c.getWidth();
		int h = c.getHeight();

		// when resize at the South
		Rectangle rect = getRectangle(0, 0, w, h, SwingConstants.SOUTH);
		if (rect.contains(me.getPoint()))
			return Cursor.S_RESIZE_CURSOR;

		// default cursor for select and drag 
		return Cursor.HAND_CURSOR;
	}
}
